<template>
    <div class="app-container">
        <!-- 搜索栏 -->
        <el-form :inline="true" :model="params" label-width="68px">
            <el-form-item label="课程名称">
                <el-input v-model="params.name" placeholder="请输入课程名称" clearable style="width: 218px;" />
            </el-form-item>
            <el-form-item label="课程类型">
                <el-select v-model="params.type" placeholder="课程类型" clearable>
                    <el-option v-for="item in types" :key="item.dictCode" :label="item.dictLabel"
                        :value="item.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="适用人群">
                <el-select v-model="params.applyTo" placeholder="适用人群" clearable>
                    <el-option v-for="item in applyTos" :key="item.dictCode" :label="item.dictLabel"
                        :value="item.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="最低价格">
                <el-input-number v-model="params.minPrice" :step="100" :precision="2" :min="0" :max="Infinity"
                    placeholder="最低价格" />
            </el-form-item>
            <el-form-item label="最高价格">
                <el-input-number v-model="params.maxPrice" :step="100" :precision="2" :min="0" :max="Infinity"
                    placeholder="最高价格" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="onSubmit">搜索</el-button>
                <el-button :icon="Refresh" @click="onReset">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 操作按钮 -->
        <el-row class="mb8" style="margin-left: -5px;margin-right: -5px;">
            <el-col class="is-guttered" :span="1.5" style="padding-left: 5px; padding-right: 5px;">
                <el-button type="primary" :icon="Plus" plain @click="openDialog()">新增</el-button>
            </el-col>
            <el-col class="is-guttered" :span="1.5" style="padding-left: 5px; padding-right: 5px;">
                <el-button type="success" :icon="Edit" plain :disabled="multipleSelection.length == 1 ? false : true"
                    @click="editCourse()">修改</el-button>
            </el-col>
            <el-col class="is-guttered" :span="1.5" style="padding-left: 5px; padding-right: 5px;">
                <el-button type="danger" :icon="Delete" plain :disabled="multipleSelection.length > 0 ? false : true"
                    @click="deleteCourse()">删除</el-button>
            </el-col>
            <el-col class="is-guttered" :span="1.5" style="padding-left: 5px; padding-right: 5px;">
                <el-button type="warning" :icon="Download" plain @click="handleExport()">导出</el-button>
            </el-col>
        </el-row>
        <!-- 表格 -->
        <el-table :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="courseId" label="课程编号" width="80" align="center" />
            <el-table-column prop="type" label="课程类型" width="120" align="center">
                <template #default="scope">
                    <el-tag v-if="scope.row.type == 1" type="">舞蹈类</el-tag>
                    <el-tag v-if="scope.row.type == 2" type="success">游泳类</el-tag>
                    <el-tag v-if="scope.row.type == 3" type="info">拳击类</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="课程名称" width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="price" label="课程价格" width="120" align="center" />
            <el-table-column prop="applyTo" label="课程适用人群" width="150" align="center">
                <template #default="scope">
                    <el-tag v-if="scope.row.applyTo == 1" type="">中小学生</el-tag>
                    <el-tag v-if="scope.row.applyTo == 2" type="success">上班族</el-tag>
                    <el-tag v-if="scope.row.applyTo == 3" type="info">小白用户</el-tag>
                    <el-tag v-if="scope.row.applyTo == 4" type="warning">健身达人</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="info" label="课程简介" width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180" align="center">
                <template #default="scope">
                    {{ scope.row.createTime.replace("T", " ") }}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" :icon="Edit" text style="padding-left: 0; padding-right: 0;"
                        @click="editCourse(scope.row.courseId)">修改</el-button>
                    <el-button type="primary" :icon="Delete" text
                        style="padding-left: 0; padding-right: 0;" @click="deleteCourse(scope.row.courseId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination v-show="total > 0" v-model:page="params.pageNum" v-model:limit="params.pageSize" :total="total"
            @pagination="listData" />

        <!-- 弹窗 -->
        <el-dialog v-model="dialogFormVisible" :title="title" width="500">
            <el-form :model="form" :rules="rules" ref="ruleFormRef">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="课程分类" label-width="80px" prop="type">
                            <el-select v-model="form.type" placeholder="课程分类" clearable>
                                <el-option v-for="item in types" :key="item.dictCode" :label="item.dictLabel"
                                    :value="Number(item.dictValue)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="课程名称" label-width="80px" prop="name">
                            <el-input v-model="form.name" placeholder="请输入课程名称" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="适用人群" label-width="80px" prop="applyTo">
                            <el-select v-model="form.applyTo" placeholder="课程适应人群" clearable>
                                <el-option v-for="item in applyTos" :key="item.dictCode" :label="item.dictLabel"
                                    :value="Number(item.dictValue)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="课程价格" label-width="80px" prop="price">
                            <el-input-number v-model="form.price" :step="100" :precision="2" :min="0" :max="Infinity"
                                placeholder="课程价格" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="课程简介" label-width="80px" prop="info">
                            <el-input v-model="form.info" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script lang="ts" setup>
import { Delete, Download, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue'
import { ComponentInternalInstance, getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
import { listCourse, addCourse, getCourse, updateCourse, delCourse } from '@/api/tienchin/course'
import { getDicts } from '@/api/system/dict/data'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// do not use same name with ref
const params = reactive({
    pageNum: 1,
    pageSize: 10,
    name: '',
    type: null,
    minPrice: null,
    maxPrice: null,
    applyTo: null,
})

// 页数
let total = ref(0)

// 课程类型
let types = ref<any[]>([])

// 适用人群
let applyTos = ref<any[]>([])

// 表格数据
let tableData = ref<any[]>([])

// 选择项
const multipleSelection = ref<any[]>([])

// 弹窗控制
const dialogFormVisible = ref(false)

// 弹窗表单
interface RuleForm {
    type: number | null
    name: string
    applyTo: number | null
    price: number | null
    info: string
}
// 弹窗表单实例
const ruleFormRef = ref<FormInstance>()

// 弹窗标题
let title = ref('')

// 弹窗表单数据
let form = ref<RuleForm>({
    type: null,
    name: '',
    applyTo: null,
    price: null,
    info: '',
})

// 弹窗表单校验规则
const rules = reactive<FormRules>({
    type: [
        { required: true, message: '课程类型不能为空', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '课程名称不能为空', trigger: 'blur' },
    ],
    applyTo: [
        { required: true, message: '适用人群不能为空', trigger: 'blur' },
    ],
    price: [
        { required: true, message: '课程价格不能为空', trigger: 'blur' },
    ],
    info: [
        { required: true, message: '课程简介不能为空', trigger: 'blur' },
    ],

})

// 搜索
const onSubmit = () => {
    listData()
}

// 重置
const onReset = () => {
    params.pageNum = 1
    params.pageSize = 10
    params.name = ''
    params.type = null
    params.minPrice = null
    params.maxPrice = null
    params.applyTo = null
    listData()
}

// 表格选择
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
}

// 列表数据
function listData() {
    listCourse(params).then((res: any) => {
        tableData.value = res.rows
        total.value = res.total
    })
}

// 字典数据
function listDicts() {
    getDicts("course_type").then((res: any) => {
        types.value = res.data
    })
    getDicts("course_apply_to").then((res: any) => {
        applyTos.value = res.data
    })
}

// 新增弹窗
const openDialog = () => {
    title.value = '添加课程'
    dialogFormVisible.value = true
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value == '添加课程') {
                addCourse(form).then(res => {
                    dialogFormVisible.value = false
                    listData()
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                })
            }
            if (title.value == '修改课程') {
                updateCourse(form.value).then(res => {
                    dialogFormVisible.value = false
                    listData()
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                })
            }

        } else {

        }
    })
}

// 修改
const editCourse = (id?: any) => {
    title.value = '修改课程'
    if (id) {
        getCourse(id).then(res => {
            dialogFormVisible.value = true
            form.value = res.data
        })
    }
    if (multipleSelection.value.length == 1) {
        getCourse(multipleSelection.value[0].courseId).then(res => {
            dialogFormVisible.value = true
            form.value = res.data
        })
    }

}

// 删除
const deleteCourse = (id?: any) => {

    let ids: any[] = []

    multipleSelection.value.forEach(item => {
        ids.push(item.courseId)
    })
    if(id){
        ids = [id]
    }

    ElMessageBox.confirm(
        '是否确认删除课程编号为' + ids.join(',') + '的数据项？',
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            delCourse(ids.join(',')).then(res => {
                listData()
                ElMessage({
                    type: 'success',
                    message: 'Delete completed',
                })
            })

        })
        .catch(() => {

        })
}

// 导出
function handleExport() {

    proxy!.download(
        'tienchin/course/export',
        {
            ...params,
        },
        `course_${new Date().getTime()}.xlsx`
    );
}

// 监听器
watch(dialogFormVisible, (newVal, oldVal) => {
    if (newVal === false) {
        form.value = {
            type: null,
            name: '',
            applyTo: null,
            price: null,
            info: '',
        }
        ruleFormRef.value?.resetFields();
    }


})

// 生命周期
onMounted(() => {
    listData()
    listDicts()
})
</script>